package com.hk.kindheartedness;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.hk.kindheartedness.db.DBOpenHelper;
import com.hk.kindheartedness.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 当前医生的所有设置的挂号记录业务处理
 */
public class QueryRegistrationActivity extends AppCompatActivity {

    //    Initialize Toast
    private Toast toast;

    //    Initialize intent
    private Intent intent;

    //    声明DBOpenHelper对象
    private DBOpenHelper dbOpenHelper;

//    ListView
    private ListView querySetADoctorListView;

    //    登录医生ID
    private String loginDoctorId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_query_registration);
//        实例化
        dbOpenHelper = new DBOpenHelper(QueryRegistrationActivity.this, "db_kindheartedness", null, 1);
//      获取ListView控制权
        querySetADoctorListView = findViewById(R.id.querySetADoctorListView);

//        获取当前登录医生Id标识
        Intent intent2 = getIntent();
        Bundle bundle = intent2.getExtras();
        loginDoctorId = bundle.getString("loginDoctorId");
        Log.i("当前登录医生ID：", loginDoctorId);

        /**
         * 查询出所有该医生的挂号设置记录并进行回显
         */
        findAByDoctorIdRegistrationSetting(loginDoctorId);

//        添加长按点击弹出选项框菜单
        querySetADoctorListView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("选择操作！");
                menu.add(0, 0, 0, "更新");
                menu.add(0, 1, 0, "删除");
            }
        });

    }

    /**
     * 给菜单项添加事件
     *
     * @param item 菜单索引
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public boolean onContextItemSelected(@NonNull MenuItem item) {
//        获取上下文
        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
//        得到listView中选择的条目绑定的Id
        String id = String.valueOf(info.id);
//        得到列表子节点的视图
        View targetView = info.targetView;
        //                获取单列 某一元素的控制权
        TextView doctorRegistrationId = targetView.findViewById(R.id.doctorRegistrationId);
//                获取元素内容 手机号
        String doctorRegistrationIdToString = doctorRegistrationId.getText().toString();
        Log.i("=====ListView列表绑定的ID==", id);
        Log.i("===== 对应的挂号记录Id==", doctorRegistrationIdToString);
        switch (item.getItemId()) {
            case 0:
//                更新事件的方法
                updateDiaLog(doctorRegistrationIdToString);
                return true;
            case 1:
//                删除事件的方法
                deleteData(doctorRegistrationIdToString);
                return true;
            default:
                return super.onContextItemSelected(item);
        }
    }

    /**
     * 根据挂号记录Id进行删除挂号记录
     * @param doctorRegistrationIdToString 挂号记录ID
     */
    private void deleteData(final String doctorRegistrationIdToString) {
        //        建立一个对话框
//                添加一个弹出对话框
        AlertDialog alertDialog = new AlertDialog.Builder(QueryRegistrationActivity.this).create();
//                设置提示
        alertDialog.setMessage("确定要删除该挂号记录吗？");
//                设置 确认按钮操作
        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确认", new DialogInterface.OnClickListener() {
            @SuppressLint("LongLogTag")
            @Override
            public void onClick(DialogInterface dialog, int which) {
//        检查当前是否已经有预约,如果有预约，则不能删除
                SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
                Cursor cursorRegistrationSetting = readableDatabase.query("registration_setting", null, "id = ?", new String[]{doctorRegistrationIdToString}, null, null, null);
                String id = null;
                String count = null;
                String remainingNumber = null;
                while (cursorRegistrationSetting.moveToNext()) {
                    id = cursorRegistrationSetting.getString(0);
                    count = cursorRegistrationSetting.getString(4);
                    remainingNumber = cursorRegistrationSetting.getString(5);
                }
                if (!count.equals(remainingNumber)) {
                    toast = ToastUtil.toastHint(toast, QueryRegistrationActivity.this, "当前已有预约，删除失败！");
                    return;
                }
                int deleteRegistrationSetting = readableDatabase.delete("registration_setting", "id = ?", new String[]{id});
                if (deleteRegistrationSetting == 1) {
                    Log.i("QueryRegistrationActivity.java", "删除成功,删除记录数：" + deleteRegistrationSetting);
                    toast = ToastUtil.toastHint(toast, QueryRegistrationActivity.this, "删除成功！");
                    intent = new Intent(QueryRegistrationActivity.this, QueryRegistrationActivity.class);
//                    重新刷新当前页面，携带当前医生ID
                    Intent intent2 = getIntent();
                    Bundle bundle = intent2.getExtras();
                    intent.putExtras(bundle);
                    startActivityForResult(intent, RESULT_OK);
                    finish();
                    return;
                }
                toast = ToastUtil.toastHint(toast, QueryRegistrationActivity.this, "删除失败,请刷新重试！");
                return;
            }
        });
//        设置取消按钮操作
        alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                toast = ToastUtil.toastHint(toast, QueryRegistrationActivity.this, "本次操作已取消！");
                return;
            }
        });
//          显示对话框
        alertDialog.show();
    }

    /**
     * 跳转到更新页面
     * @param doctorRegistrationIdToString 挂号记录ID
     */
    private void updateDiaLog(String doctorRegistrationIdToString) {
//        检查当前是否已经有预约,如果有预约，则不能更新
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
        Cursor cursorRegistrationSetting = readableDatabase.query("registration_setting", null, "id = ?", new String[]{doctorRegistrationIdToString}, null, null, null);
        String count = null;
        String remainingNumber = null;
        while (cursorRegistrationSetting.moveToNext()) {
            count = cursorRegistrationSetting.getString(4);
            remainingNumber = cursorRegistrationSetting.getString(5);
        }
        if (!count.equals(remainingNumber)) {
            toast = ToastUtil.toastHint(toast, QueryRegistrationActivity.this, "当前已有预约，不能更新！");
            return;
        }
//        跳转到更新页面
        intent = new Intent(QueryRegistrationActivity.this,RegistrationSettingUpdateActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("registrationSettingId",doctorRegistrationIdToString);
        intent.putExtras(bundle);
        startActivity(intent);
        QueryRegistrationActivity.this.finish();
    }

    /**
     * 查询当前医生的所有挂号设置记录
     * @param loginDoctorId 医生Id（唯一标识）
     */
    private void findAByDoctorIdRegistrationSetting(String loginDoctorId) {
//        获取打开的数据库
        SQLiteDatabase readableDatabase = dbOpenHelper.getReadableDatabase();
//        查询当前医生所设置的挂号记录
        Cursor cursorRegistrationSetting = readableDatabase.query("registration_setting", null, "doctor_id = ? ", new String[]{loginDoctorId}, null, null, "registration_date asc,registration_time asc");
        //        存储获取到的数据
        List<Map<String, Object>> resultList = new ArrayList<>(10);
        while (cursorRegistrationSetting.moveToNext()) {
            Map<String, Object> map = new HashMap<>(6);
            String id = cursorRegistrationSetting.getString(0);
            String registrationDate = cursorRegistrationSetting.getString(2);
            String registrationTime = cursorRegistrationSetting.getString(3);
            String count = cursorRegistrationSetting.getString(4);
            String remainingNumber = cursorRegistrationSetting.getString(5);
            String registrationMoney = cursorRegistrationSetting.getString(6);
            map.put("id",id);
            map.put("registrationDate",registrationDate+"\n"+registrationTime);
            map.put("registrationMoney",registrationMoney);
            map.put("count",count);
            map.put("remainingNumber",remainingNumber);
//                将封装的map集合存储到resultList集合中
            resultList.add(map);
        }
//        判断是否具有挂号记录
        if (resultList == null || resultList.size() == 0) {
            toast = ToastUtil.toastHint(toast, QueryRegistrationActivity.this, "暂无挂号记录，请稍后查看！");
            return;
        }
        SimpleAdapter simpleAdapter = new SimpleAdapter(
                QueryRegistrationActivity.this,
                resultList,
                R.layout.query_registration,
                new String[]{
                        "id",
                        "registrationDate", "registrationMoney",
                        "count", "remainingNumber"
                },
                new int[]{
                        R.id.doctorRegistrationId,
                        R.id.setADoctorTime2, R.id.registrationMoney,
                        R.id.registrationCount, R.id.remainingNumber
                }
        );
        querySetADoctorListView.setAdapter(simpleAdapter);
    }

    /**
     * 断开数据库连接
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbOpenHelper != null) {
            dbOpenHelper.close();
        }
    }

}